<template>
    <el-container>
        <div class="el-tabs">
            <div class="el-tabs_item">
                <span class="subtitle">概览</span>
                <el-icon><refresh /></el-icon>
            </div>
            <div
                class="el-tabs_item"
                :class="{ active: item.status === state }"
                v-for="item in tabs"
                :key="item.status"
                @click="getList(item.status)"
            >
                <span>
                    <el-icon><component :is="item.icon" /></el-icon> {{ item.title }}
                </span>
                <el-badge :value="item.value" :max="99" :type="item.type" class="sup" />
            </div>
        </div>
        <el-container class="el-content">
            <el-form :inline="true" class="table-filter el-box-init el-bkgd-white">
                <el-form-item label="博文标题" class="el-mg-r-30">
                    <el-input v-model="keywor" clearable placeholder="请输入文章标题" />
                </el-form-item>
                <el-form-item>
                    <el-button type="success" round @click="onSearch">
                        <el-icon class="table-icon"><search /></el-icon>
                        查询
                    </el-button>
                    <el-button type="warning" round @click="onReset">
                        <el-icon class="table-icon"><refresh /></el-icon>
                        重置
                    </el-button>
                </el-form-item>
            </el-form>

            <div class="table-wrap el-box-init el-bkgd-white">
                <div class="table-btn el-pd-b-20">
                    <el-button
                        type="primary"
                        v-if="isAuth('BLOG_ARTICLE_ADD') && state != 3"
                        @click="onAddOrUpdate()"
                    >
                        <el-icon class="table-icon"><plus /></el-icon>
                        新增
                    </el-button>
                    <el-button
                        type="warning"
                        v-if="isAuth('BLOG_ARTICLE_SORT') && state != 3"
                        @click="onUpdateSort()"
                    >
                        <el-icon class="table-icon"><refresh /></el-icon>
                        更新排序
                    </el-button>
                    <el-button
                        type="success"
                        v-if="
                            allDelBtnVisible &&
                            isAuth('BLOG_ARTICLE_PUBLISH') &&
                            state != 3 &&
                            state != 1
                        "
                        @click="articleStateChange(1)"
                    >
                        批量发布
                    </el-button>
                    <el-button
                        type="warning"
                        v-if="allDelBtnVisible && isAuth('BLOG_ARTICLE_RECYCLE')"
                        @click="articleStateChange(state != 2 && state != 0 ? 2 : 3)"
                    >
                        {{ state != 2 && state != 0 ? '批量草稿' : '批量回收' }}
                    </el-button>
                    <el-button
                        type="danger"
                        v-if="allDelBtnVisible && isAuth('BLOG_ARTICLE_DEL')"
                        @click="onDel()"
                    >
                        <el-icon class="table-icon"><delete /></el-icon>
                        批量删除
                    </el-button>
                </div>

                <el-table
                    v-loading="loading"
                    :data="list"
                    stripe
                    border
                    ref="tableRef"
                    @selection-change="handleSelectionChange"
                    :row-key="getRowKeys"
                >
                    <el-table-column type="selection" width="40" />
                    <el-table-column prop="id" label="博文ID" width="80" />
                    <el-table-column prop="title" label="博文标题" />
                    <el-table-column prop="status" label="状态" v-if="state == 0" align="center">
                        <template #default="{ row }">
                            <el-tag
                                v-for="tag in tabs"
                                :key="tag.status"
                                v-show="tag.status == row.status"
                                :type="tag.type"
                            >
                                {{ tag.title }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="support"
                        label="是否推荐"
                        width="100"
                        align="center"
                        v-show="state != 3"
                    >
                        <template #default="{ row }">
                            <el-tag :type="row.support == 1 ? 'success' : 'warning'">
                                {{ row.support == 1 ? '是' : '否' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="click"
                        label="浏览量"
                        width="80"
                        align="center"
                        v-if="state != 3"
                    />
                    <el-table-column prop="issuer_name" label="创建人" width="100" align="center" />
                    <el-table-column prop="created_time" label="创建时间" width="100">
                        <template #default="{ row }">
                            {{ formatTime(row.created_time) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        :width="$maxActionWidth"
                        align="center"
                        fixed="right"
                    >
                        <template #default="{ row }">
                            <div class="handle-wrap">
                                <el-button
                                    type="success"
                                    v-if="row.status == 1"
                                    @click="
                                        this.$router.push({
                                            name: 'Info_article_talk',
                                            query: { article_id: row.id }
                                        })
                                    "
                                >
                                    评论
                                </el-button>

                                <el-button
                                    type="primary"
                                    v-if="isAuth('BLOG_ARTICLE_ADD')"
                                    @click="onAddOrUpdate(row.id)"
                                >
                                    <el-icon class="table-icon"><edit /></el-icon>
                                    编辑
                                </el-button>
                                <el-button
                                    type="success"
                                    v-if="isAuth('BLOG_ARTICLE_PUBLISH') && row.status == 2"
                                    @click="articleStateChange(1, row.id)"
                                >
                                    发布
                                </el-button>

                                <el-button
                                    type="warning"
                                    v-if="isAuth('BLOG_ARTICLE_DEL')"
                                    @click="articleStateChange(row.status == 2 ? 3 : 2, row.id)"
                                >
                                    {{ row.status == 2 ? '回收' : '草稿' }}
                                </el-button>

                                <el-button
                                    type="danger"
                                    v-if="isAuth('BLOG_ARTICLE_DEL')"
                                    @click="onDel(row.id)"
                                >
                                    <el-icon class="table-icon"><delete /></el-icon>
                                    删除
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <el-pagination
                    :currentPage="currentPage"
                    :page-size="pageSize"
                    :page-sizes="pageSizes"
                    background
                    :layout="layout"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-container>

        <!-- 新增、编辑 -->
        <dialog-add-or-update
            ref="addOrUpdate"
            @eventUpdate="initTableSelectionIds"
        ></dialog-add-or-update>
    </el-container>
</template>

<script>
import { getCurrentInstance, reactive, toRefs, ref } from 'vue';
import { adminArticle as Api } from 'api';
import { mixins } from '@/global/utils/mixins';
import DialogAddOrUpdate from './add-or-update.vue';

export default {
    mixins: [mixins],
    components: {
        DialogAddOrUpdate
    },
    setup() {
        const { proxy } = getCurrentInstance();
        let tabs = ref([]);
        let state = ref(0);
        let allDelBtnVisible = ref(false);
        let search = reactive({
            keywor: ''
        });
        // 表格
        let table = reactive({
            loading: false,
            rowId: 0,
            list: [],
            currentPage: proxy.$config.pagination.currentPage, // 默认页
            pageSize: proxy.$config.pagination.pageSize, // 每页多少条
            pageSizes: proxy.$config.pagination.pageSizes, // 每页显示个数下拉选择器的选项设置
            layout: proxy.$config.pagination.layout, // 组件布局，子组件名用逗号分隔
            total: 0 // 总条数
        });
        // 回显选过的列
        const getRowKeys = (row) => row.id;

        // 获取tabs列表
        const getTabs = async () => {
            const { code, data } = await proxy.$http.get(Api.getTabs);

            if (code === 200) {
                const list = proxy.$utils.getTabs(data.list);
                tabs.value = list;
            }
        };
        // 获取文章列表
        const getList = async (status = 0) => {
            const { code, data } = await proxy.$http.get(Api.getList, {
                params: {
                    status: status,
                    keywor: search.keywor,
                    page: table.currentPage, //查询第几页
                    per_page: table.pageSize //每页多少条数据
                }
            });

            if (code === 200) {
                state.value = status;
                table.list = data.list;
                table.total = data.total;

                table.loading = false;
            }
        };
        // 文章状态操作
        const articleStateChange = async (status, id) => {
            if (!id) id = table.selectIds.map((item) => item.id).join(',');
            // 确认删除
            const confirm = await proxy.$msgBox.confirm({
                cancel: true,
                msg: `您当前操作会变更文章状态`
            });

            if (confirm) {
                const { code, msg, data } = await proxy.$http.put(Api.articleStateChange, {
                    id,
                    status
                });

                if (code === 200) {
                    proxy.$msg.success(msg);
                    initTableSelectionIds();
                } else {
                    proxy.$msg.error(msg ? msg : data);
                }
            }
        };
        // 排序
        const onUpdateSort = async () => {
            const sortList = table.list.map((item, index) => ({
                id: item.id,
                sort: index + (table.currentPage - 1) * table.pageSize
            }));

            const { code, msg, data } = await proxy.$http.post(Api.onUpdateSort, {
                sortList: JSON.stringify(sortList)
            });

            if (code === 200) {
                proxy.$msg.success(msg);
                // 初始化清除表格选中、刷新
                initTableSelectionIds();
            } else {
                proxy.$msg.error(msg ? msg : data);
            }
        };
        // 删除
        const onDel = async (id) => {
            if (!id) id = table.selectIds.map((item) => item.id).join(',');

            const confirm = await proxy.$msgBox.confirm({ cancel: true });

            if (confirm) {
                const { code, msg, data } = await proxy.$http.delete(Api.del, {
                    data: { id }
                });

                if (code === 200) {
                    proxy.$msg.success(msg);
                    // 初始化清除表格选中、刷新
                    initTableSelectionIds();
                } else {
                    proxy.$msg.error(msg ? msg : data);
                }
            }
        };

        // 查询
        const onSearch = () => {
            table.loading = true;
            // 初始化清除表格选中、刷新
            initTableSelectionIds();
        };
        // 重置
        const onReset = () => {
            search.keywor = '';
        };
        // 新增、编辑
        const onAddOrUpdate = (id) => {
            proxy.$refs.addOrUpdate.id = id;
            proxy.$refs.addOrUpdate.visible = true; // 弹窗开关
        };
        // 表格全选
        const handleSelectionChange = (rows) => {
            table.selectIds = rows;
            allDelBtnVisible.value = table.selectIds.length ? true : false;
        };
        // 每页多少条
        const handleSizeChange = (val) => {
            table.loading = true;
            table.pageSize = val;
            initTableSelectionIds();
        };
        // 当前页
        const handleCurrentChange = (val) => {
            table.loading = true;
            table.currentPage = val;
            initTableSelectionIds();
        };
        // 初始化清除表格选中、全选数组、表格刷新
        const initTableSelectionIds = () => {
            proxy.$refs.tableRef.clearSelection(); // 清除表格选择
            table.selectIds = [];
            getTabs();
            getList();
        };

        const formatTime = (value) => {
            return proxy.$formatTime(value);
        };

        getTabs();
        getList().then(() => {
            proxy.rowDrop();
        });

        return {
            tabs,
            state,
            ...toRefs(table),
            ...toRefs(search),
            allDelBtnVisible,
            getRowKeys,
            articleStateChange,
            onUpdateSort,
            onDel,
            onSearch,
            onReset,
            onAddOrUpdate,
            handleSelectionChange,
            handleSizeChange,
            handleCurrentChange,
            formatTime,
            getList,
            initTableSelectionIds
        };
    }
};
</script>

<style lang="less" scoped>
.main {
    display: flex;
    height: 100%;
}
.el-tabs {
    display: flex;
    flex-direction: column;
    width: 200px;
    min-width: 200px;
    background: #fff;

    .el-tabs_item {
        height: 40px;
        padding: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #f0f2f5;
        cursor: pointer;

        .sup {
            /deep/ .el-badge__content {
                border-radius: 5px !important;
            }
        }
    }
    .el-tabs_item:not(:nth-child(1)) {
        padding: 10px 10px 0;
        // padding: 0;

        &:hover {
            background: #f0f2f5;
        }
    }

    .el-tabs_item.active {
        background: #f0f2f5;
    }
}

.el-content {
    flex-direction: column;
    margin-left: 15px;
}
</style>
